package com.tianhui.consignortwofei.mvp.ui.activity.hetong;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.fgs.common.CommonResponse;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;

import com.fgs.common.update.FileUtils;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.dialog.OperateTipDialog;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.api.hetong.HuRequest;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractInfo;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractModel;
import com.tianhui.consignortwofei.mvp.model.hetong.HeTongXiaZaiBean;
import com.tianhui.consignortwofei.mvp.model.hetong.ProductInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.HeTongWatchActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.activity.ContractAddStepOneActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.activity.edit.EditContractStepOneActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.adapter.ContractListAdapter;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.contract.ContractListContract;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.impl.HeTongIOrderStatus;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.presenter.ContractListPresenter;
import com.tianhui.consignortwofei.other.EventWhat;

import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class ContractListFragment extends HeTongSearchFragment<ContractListContract.View, ContractListContract.Presenter> implements ContractListContract.View {

    private HeTongIOrderStatus mIOrderStatus;
    private String mSearchKey;

    private ContractModel contractModel;
    private HuRequest huRequest;

    public ContractListFragment() {
        // Required empty public constructor
        contractModel = new ContractModel();
    }

    @Override
    public boolean isNeedLazyLoad() {
        return false;
    }

    public static ContractListFragment newInstance(HeTongIOrderStatus iOrderStatus) {
        ContractListFragment orderListFragment = new ContractListFragment();
        orderListFragment.setOrderStatus(iOrderStatus);

        return orderListFragment;
    }

    public ContractListFragment setOrderStatus(HeTongIOrderStatus iOrderStatus) {
        mIOrderStatus = iOrderStatus;
        return this;
    }

    public ContractListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }


    @Override
    protected ContractListContract.View createView() {
        huRequest = new HuRequest();
        return this;
    }

    @Override
    protected ContractListContract.Presenter createPresenter() {
        return new ContractListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new ContractListAdapter(getContext(), mIOrderStatus);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                ContractInfo contractInfo = null;
                if (object instanceof ContractInfo) {
                    contractInfo = (ContractInfo) object;
                }
                switch (view.getId()) {
                    case R.id.item_contract_list_createTextView:
                        showCreateTipDialog(contractInfo);
                        break;
                    case R.id.item_contract_list_downloadTextView:
                        downloadContract(contractInfo);
                        break;
                    case R.id.tv_download_pingzheng:
                        downloadPingZheng(contractInfo);
                        break;

                    case R.id.item_contract_list_editTextView:
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
//                            openActivity(EditContractStepOneActivity.class, bundle);
                            openActivity(EditContractStepOneActivityNew.class, bundle);
                        }
                        break;
                    case R.id.item_contract_list_watch:
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
//                            openActivity(EditContractStepOneActivity.class, bundle);
                            openActivity(HeTongWatchActivity.class, bundle);//查看合同
//                            openActivity(LiuChengJieDianActivity.class, bundle);//流程显示
//                            openActivity(HeTongShenPiBossActivity.class, bundle);//审核页面

                        }
                        break;
                    case R.id.item_contract_watch_liucheng:
                        if (contractInfo != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, contractInfo);
                            openActivity(LiuChengJieDianActivity.class, bundle);//流程显示
                        }

                        break;



                }
            }
        });

    }

    private void showCreateTipDialog(ContractInfo contractInfo) {
        new MaterialDialog.Builder(getContext())
                .content("是否生成提交？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        createContract(contractInfo);
                    }
                })
                .show();
    }





    private void createContract(ContractInfo contractInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", contractInfo.id);
        map.put("type", "1");
        contractModel.createContractModel(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                showToast(commonResponse.getMsg());
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }


    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog,huRequest,page);
        }
    }



    @Override
    public void initData() {
        mUserInfoModel = new UserInfoModel();

        if (mIOrderStatus != null)
            setSearchKeyHint(mIOrderStatus.getSearchHint());
    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_CONTRACT_LIST:
                if (isHasLoadData())
                    refreshData(false);
                break;
            case CHANGE_TAB_FRAGMENT:
        }
    }

    @OnClick(R.id.fragment_contract_list_addContractButton)
    public void addContract() {
        openActivity(ContractAddStepOneActivityNew.class);
//        openActivity(ContractAddStepOneActivity.class);
//        openActivity(ContractAddStepFourActivity.class);
    }





    private UserInfoModel   mUserInfoModel;
    private void downloadContract(ContractInfo contractInfo) {

        //检查存储权限
        new PermissionHelper().checkPermissions(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {
                String fileName = "hetong"+contractInfo.contractno;
                new OperateTipDialog.Builder(getActivity())
                        .title("文件名称")
                        //                .content("存在多个牌号重量用逗号(,)隔开，调整数字即可，必须保留逗号。")
                        .input(fileName,new OperateTipDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {

                            }
                        })
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive(new OperateTipDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull OperateTipDialog dialog) {
                                String reason = dialog.getInputContent();
                                if (TextUtils.isEmpty(reason)) {
                                    ToastUtil.showShortToast("文件名称不能为空");
                                    return;
                                }
                                dialog.dismiss();
//                                downloadPing(contractInfo,allNumber,reason+".pdf");
                                downloadHeTOng(contractInfo,reason+".pdf");
                            }
                        })
                        .show();

            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }

        });


    }

    private void downloadHeTOng(ContractInfo contractInfo,String fileName) {
//        String fileName = "hetong"+contractInfo.contractno+".pdf";
        Map<String, String> map = new HashMap<>();
        map.put("contractno",contractInfo.contractno);
        mUserInfoModel.downloadContract(getActivity(), map, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse<HeTongXiaZaiBean>>() {
                    @Override
                    public void onNext(CommonResponse<HeTongXiaZaiBean> commonResponse) {
                        if (commonResponse.getCode() == 20000) {
                            String base64Data = commonResponse.getData().getPdfContent();
                            convertToGifAndProcess(base64Data,fileName);
                        } else {
                            showToast(commonResponse.getMsg());
                        }

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        showToast(e.message);
                    }
                });
    }


    private void downloadPingZheng(ContractInfo contractInfo) {//下载确认函

        //检查存储权限
        new PermissionHelper().checkPermissions(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {
//                downloadPing(contractInfo);
                showTerminateDialog(contractInfo);
            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }

        });


            ////        String url = Config.baseUrl + "contract/download?id=" + contractInfo.id;
            //        String token = SharedPreferenceManager.getInstance().getToken();
            //        String url = Config.baseUrl + "contract/downloadReceiptFile?contractno=" + contractInfo.contractno;
            ////        Uri uri = Uri.parse(url);
            ////        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            ////        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ////        startActivity(intent);
            //
            //        // 假设你已经有了一个有效的token字符串
            ////        String token = "your_token_here";
            //
            //        // 创建一个Intent来启动浏览器
            //        Intent intent = new Intent(Intent.ACTION_VIEW);
            //
            //        // 构建带有query参数的URL，参数名为你的token
            //        // 假设你的参数名是 "auth_token"
            //        Uri uri = Uri.parse(url)
            //                .buildUpon()
            //                .appendQueryParameter("Authorization", token)
            //                .build();
            //
            //        // 设置Intent的数据为包含token的URL
            //        intent.setData(uri);
            //        // 添加一个判断，如果有多个浏览器可用，允许用户选择
            //        intent.addCategory(Intent.CATEGORY_BROWSABLE);
            //        startActivity(intent);


    }

    private void downloadPing(ContractInfo contractInfo,String allNumber,String fileName) {

        Map<String, String> map = new HashMap<>();
        map.put("contractno",contractInfo.contractno);
        map.put("weight",allNumber);//weight

        mUserInfoModel.downloadPingZheng(getActivity(), map, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse<HeTongXiaZaiBean>>() {
                    @Override
                    public void onNext(CommonResponse<HeTongXiaZaiBean> commonResponse) {
                        if (commonResponse.getCode() == 20000) {
                            String base64Data = commonResponse.getData().getPdfContent();
                            convertToGifAndProcess(base64Data,fileName);
                        } else {
                            showToast(commonResponse.getMsg());
                        }

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        showToast(e.message);
                    }
                });
    }


    /**
     * 转换成file
     * @param base64
     */
    private void convertToGifAndProcess(String base64,String fileName) {
        File gifFile = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
//        File gifFile = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
        saveFileToPath(base64, gifFile);


       //下载完成操作
        Uri imageUir;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUir = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".fileProvider", gifFile);
        } else {
            imageUir = Uri.fromFile(gifFile);
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUir);
        shareIntent.setType("*/*");
        startActivity(Intent.createChooser(shareIntent, "分享"));


    }
    /**
     * 保存文件
     * @param base64
     * @param gifFilePath
     */
    private void saveFileToPath(String base64, File gifFilePath) {
        try {
            byte[] fileBytes = Base64.decode(base64.replaceFirst(
                    "data:image/gif;base64,", ""), 0);
            FileOutputStream os = new FileOutputStream(gifFilePath, false);
            os.write(fileBytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 清除下载的cache文件
     *
     * @param filePath 要删除文件的绝对路径
     */
    public void clearCacheFile(String filePath) {
        if (StringUtils.isEmpty(filePath))
            return;

        FileUtils.delFile(filePath);
    }


    private String allNumber="";
    private void showTerminateDialog(ContractInfo contractInfo) {
        List<ProductInfo> contractcontentlist = contractInfo.contractcontentlist;
        allNumber="";
        for (int i=0;i<contractcontentlist.size();i++){
            String number = contractcontentlist.get(i).number;
            if (0==i){
                allNumber=number;
            }else {
                allNumber=allNumber+","+number;
            }

        }




        new OperateTipDialog.Builder(getActivity())
                .title("确认收货函吨位\n\n存在多个牌号重量用逗号(,)隔开，调整数字即可，必须保留逗号。")
//                .content("存在多个牌号重量用逗号(,)隔开，调整数字即可，必须保留逗号。")
                .input(allNumber,new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {

                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("收货吨位不能为空");
                            return;
                        }
                        allNumber=reason;
                        dialog.dismiss();

                                String fileName = "pingzheng"+contractInfo.contractno;
                                new OperateTipDialog.Builder(getActivity())
                                        .title("文件名称")
        //                .content("存在多个牌号重量用逗号(,)隔开，调整数字即可，必须保留逗号。")
                                        .input(fileName,new OperateTipDialog.InputCallback() {
                                            @Override
                                            public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {

                                            }
                                        })
                                        .positiveText("确定")
                                        .negativeText("取消")
                                        .onPositive(new OperateTipDialog.SingleButtonCallback() {
                                            @Override
                                            public void onClick(@NonNull OperateTipDialog dialog) {
                                                String reason = dialog.getInputContent();
                                                if (TextUtils.isEmpty(reason)) {
                                                    ToastUtil.showShortToast("文件名称不能为空");
                                                    return;
                                                }
                                                dialog.dismiss();
                                                downloadPing(contractInfo,allNumber,reason+".pdf");

                                            }
                                        })
                                        .show();

//                        downloadPing(contractInfo,allNumber);

                    }
                })
                .show();
    }





}
